<template>
<div>
  <!--  面包屑导航-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>角色列表</el-breadcrumb-item>
  </el-breadcrumb>
<!--  卡片-->
  <el-card>
    <el-row>
      <el-col :span="6">
          <el-button type="primary" @click="isboolAddDialogVisible">添加角色</el-button>
      </el-col>
    </el-row>
<!--    table数据展示-->
    <el-table :data="rolesData" stripe border>
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row :class="['bdbottom',index === 0 ? 'bdtop':'','vcenter']" v-for="(item,index) in scope.row.children" :key="item.id">
            <el-col :span="5">
              <el-tag closable @close="removeRolesById(scope.row,item.id)">{{item.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <el-col :span="19">
              <el-row :class="['bdbottom','vcenter']" v-for="item1 in item.children" :key="item1.id">
                <el-col :span="8">
                  <el-tag closable @close="removeRolesById(scope.row,item1.id)" type="success">{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="16">
                  <el-tag closable @close="removeRolesById(scope.row,item2.id)" type="warning" v-for="item2 in item1.children" :key="item2.id">{{item2.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="修改角色" placement="top" :enterable="false">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editRolesInfo(scope.row.id)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除角色" placement="top" :enterable="false">
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRoles(scope.row.id)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="分配权限" placement="top" :enterable="false">
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="setRights(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
<!--  分配权限-->
  <el-dialog
    @close="setRightsDialog"
    title="提示"
    :visible.sync="showSetRightDialogVisible"
    width="70%">
<!--    树形控件 default-expand-all:是否默认展开所有节点 default-checked-keys:默认勾选的节点的 key 的数组-->
    <el-tree
      ref="treeRef"
      :data="rightsList"
      :default-checked-keys="defaultKey"
      node-key="id"
      default-expand-all
      :props="rightsProps"
      show-checkbox>
    </el-tree>
    <span slot="footer" class="dialog-footer">
    <el-button @click="showSetRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRolesRights">确 定</el-button>
  </span>
  </el-dialog>
<!--  添加用户-->
  <el-dialog
    @close = 'closeAddDialog'
    title="添加用户"
    :visible.sync="addDialogVisible"
    width="70%">
    <!--    添加用户表单-->
    <el-form :model="addRolesData" :rules="addRolesRules" ref="addRolesRuleForm" label-width="100px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="addRolesData.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="addRolesData.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="isboolAddDialogVisible">取 消</el-button>
    <el-button type="primary" @click="addRoles">确 定</el-button>
  </span>
  </el-dialog>
  <!--  修改角色对话框-->
  <el-dialog
    @close = 'closeEditDialog'
    title="修改用户"
    :visible.sync="editDialogVisible"
    width="70%">
    <!--    修改用户表单-->
    <el-form :model="addRolesData" :rules="addRolesRules" ref="editUserRuleForm" label-width="100px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="addRolesData.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="addRolesData.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="isboolEditDialogVisible">取 消</el-button>
    <el-button type="primary" @click="editRoles">确 定</el-button>
  </span>
  </el-dialog>
</div>
</template>

<script>
export default {
  name: 'roles',
  data () {
    return {
      rolesData: [],
      // 分配权限对话框显示与隐藏
      showSetRightDialogVisible: false,
      // 添加角色对话框显示与隐藏
      addDialogVisible: false,
      // 修改用户对话框显示隐藏
      editDialogVisible: false,
      // 所有权限列表
      rightsList: [],
      // 设置显示节点
      rightsProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认勾选
      defaultKey: [],
      // 当前分配权限的id
      rolesId: '',
      // 添加角色表单数据
      addRolesData: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色表单验证规则
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入角色', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getRolesData()
  },
  methods: {
    async getRolesData () {
      const { data } = await this.$axios.get('roles')
      if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
      this.rolesData = data.data
      console.log(this.rolesData)
    },
    // 删除角色指定权限
    removeRolesById (role, id) {
      this.$confirm('此操作将永久删除该角色指定权限, 是否继续?', '确定删除吗', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 确认删除
        const { data } = await this.$axios.delete(`roles/${role.id}/rights/${id}`)
        this.$message.success(data.meta.msg)
        // 为了不关闭标签重新渲染
        role.children = data.data
      }).catch(() => {
        this.$message.info('取消删除成功')
      })
    },
    // 分配权限
    async setRights (role) {
      this.rolesId = role.id
      // 得到所有权限
      const { data } = await this.$axios.get('rights/tree')
      if (data.meta.status !== 200) return this.$message.error('data.meta.msg')
      this.rightsList = data.data
      console.log(this.rightsList)
      this.getLeafKeys(role, this.defaultKey)
      this.showSetRightDialogVisible = true
    },
    // 递归函数获取角色所有三级权限id
    getLeafKeys (node, arr) {
      // 如果当前接待你不包含children代表是三级节点 把id保存到arr中
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听对话框关闭事件
    setRightsDialog () {
      this.defaultKey = []
    },
    // 点击确定按钮发送请求修改角色的指定权限
    async setRolesRights () {
      const setRightsId = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const setRightsIdStr = setRightsId.join(',')
      const { data } = await this.$axios.post(`roles/${this.rolesId}/rights`, { rids: setRightsIdStr })
      if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
      this.$message.success(data.meta.msg)
      this.getRolesData()
      this.showSetRightDialogVisible = false
    },
    // 删除角色
    deleteRoles (id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async res => {
        const { data } = await this.$axios.delete(`roles/${id}`)
        if (data.meta.status !== 200) return this.$message.info(data.meta.msg)
        this.$message.info(data.meta.msg)
        this.getRolesData()
      }).catch(() => {
        this.$message.info('取消删除该角色成功')
      })
    },
    // 点击添加角色弹出对话框
    isboolAddDialogVisible () {
      this.addRolesData = {}
      this.addDialogVisible = !this.addDialogVisible
    },
    // 点击修改角色弹出对话框
    isboolEditDialogVisible () {
      this.editDialogVisible = !this.editDialogVisible
    },
    // 监听添加角色对话框关闭事件
    closeAddDialog () {
      this.$refs.addRolesRuleForm.resetFields()
    },
    // 添加角色
    addRoles () {
      this.$refs.addRolesRuleForm.validate(async bool => {
        if (bool) {
          const { data } = await this.$axios.post('roles', this.addRolesData)
          if (data.meta.status !== 201) return this.$message.error(data.meta.msg)
          this.$message.success(data.meta.msg)
          this.getRolesData()
          this.addDialogVisible = false
        } else {
          this.$message.error('请填写必填字段')
        }
      })
    },
    // 获取角色信息
    async editRolesInfo (id) {
      const { data } = await this.$axios.get(`roles/${id}`)
      if (data.meta.status === 200) {
        // 获取角色信息成功
        this.addRolesData = data.data
      } else {
        this.$message.error(data.meta.msg)
      }
      this.editDialogVisible = !this.editDialogVisible
    },
    closeEditDialog () {
      this.$refs.editUserRuleForm.resetFields()
    },
    // 修改角色
    editRoles () {
      this.$refs.editUserRuleForm.validate(async bool => {
        if (bool) {
          const { data } = await this.$axios.put(`roles/${this.addRolesData.roleId}`, this.addRolesData)
          if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
          this.$message.success(data.meta.msg)
          this.isboolEditDialogVisible()
          this.getRolesData()
        } else {
          this.$message.error('请填写必填字段')
        }
      })
    }
  }
}
</script>

<style scoped>
.el-tag{
  margin:7px;
}
.bdtop{
  border-top: 1px solid #ccc;
}
.bdbottom{
  border-bottom: 1px solid #ccc;
}
.vcenter{
  display: flex;
  align-items: center;
}
.el-row:nth-last-child(1){
  border-bottom: none;
}
</style>
